package cn.doitedu.javase.calculate_engine.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class HttpExpressionTask implements Runnable{

    ServerSocket httpServerSocket;
    HashMap<String, RequestHandler> handlerHashMap = new HashMap<>();

    public HttpExpressionTask(ServerSocket httpServerSocket) {
        this.httpServerSocket = httpServerSocket;

        // 路由表
        handlerHashMap.put("/index.html",new IndexHandler());
        handlerHashMap.put("/favicon.ico",new FaviconHandler());

    }

    @Override
    public void run() {
        while(true){
            try {
                Socket socket = httpServerSocket.accept();

                InputStream inputStream = socket.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

                OutputStream outputStream = socket.getOutputStream();

                // 读请求的第一行
                String requestFirstLine = br.readLine();
                System.out.println(requestFirstLine);

                /* *
                 * 解析http的请求头
                 */
                UrlAndParams urlAndParams = HttpRequestParser.parseHeaderFirst(requestFirstLine);
                System.out.println(urlAndParams);

                /**
                 * 路由表
                 *    /index.html -->  处理器
                 *    /add_express --> 处理器
                 *    /login.html -->  处理器
                 */
                RequestHandler requestHandler = handlerHashMap.get(urlAndParams.getUrl());
                // 如果客户端请求的地址没有对应的handler
                if(requestHandler == null ){
                    // 就使用默认的404 handler来处理这个请求
                    requestHandler = new DefaultHandler();
                }

                byte[] bytes = requestHandler.handlerRequest(urlAndParams);

                // 输出给浏览器
                outputStream.write(bytes);
                outputStream.flush();


                outputStream.close();
                inputStream.close();
                socket.close();


            }catch (Exception ignored){
                ignored.printStackTrace();

            }
        }

    }
}
